import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:qr_code_scanner/qr_code_scanner.dart';
import 'package:scan/QrCreatePage.dart';

import 'package:image_picker/image_picker.dart';

import 'MyRecognitionQrcode.dart';
///扫码页
class ScanPage extends StatefulWidget {
  const ScanPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return ScanState();
  }
}

class ScanState extends State<ScanPage> with SingleTickerProviderStateMixin  {
  Barcode? result;
  QRViewController? controller;

  bool isFlashOn = false;

  String content = "";
  final GlobalKey qrKey = GlobalKey(debugLabel: 'QR');

  // In order to get hot reload to work we need to pause the camera if the platform
  // is android, or resume the camera if the platform is iOS.
  @override
  void reassemble() {
    super.reassemble();
    if (Platform.isAndroid) {
      controller!.pauseCamera();
    }
    controller!.resumeCamera();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          _buildQrView(context),

          Positioned(
              top: 50,
              left: 20,
              child: GestureDetector(
                child: const Icon(
                  Icons.arrow_back_ios,
                  color: Colors.white,
                ),
                onTap: () {
                  controller?.pauseCamera();
                  Navigator.pop(context);
                },
              )),

          Positioned(
            right: 20,
            top: 50,
            child: GestureDetector(
              child: const Text(
                "生成",
                style: TextStyle(color: Colors.white),
              ),
              onTap: () async {
                controller?.pauseCamera();
                await Navigator.push(context, MaterialPageRoute(builder: (context) {
                  return const QrCreatePage();
                }));
                controller?.resumeCamera();
              },
            ),
          ),

          Positioned(
            bottom: 30,
            left: 30,
            child: GestureDetector(
              child: Icon(
                isFlashOn ? Icons.flashlight_on : Icons.flashlight_off,
                color: Colors.white,
              ),
              onTap: () {
                controller?.toggleFlash();
                setState(() {
                  isFlashOn = !isFlashOn;
                });
              },
            ),
          ),

          Positioned(
            bottom: 30,
            right: 30,
            child: GestureDetector(
              child: const Icon(
                Icons.image,
                color: Colors.white,
              ),
              onTap: () {
                final picker = ImagePicker();
                picker.getImage(source: ImageSource.gallery).then((value) {
                  if(value?.path == null) {
                    Fluttertoast.showToast(msg: "未选择图片");
                  } else {
                    //支持base64、url(服务端图片：https://www.baidu.com/test.png)、filePath三种方式
                    MyRecognitionQrcode.recognition(value?.path).then((result) {
                      content = result['value'];

                      showResultPop();
                    });
                  }
                }); //
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildQrView(BuildContext context) {
    // For this example we check how width or tall the device is and change the scanArea and overlay accordingly.
    // var scanArea = (MediaQuery.of(context).size.width < 400 ||
    //         MediaQuery.of(context).size.height < 400)
    //     ? 260.0
    //     : 360.0;
    // To ensure the Scanner view is properly sizes after rotation
    // we need to listen for Flutter SizeChanged notification and update controller
    return QRView(
      key: qrKey,
      onQRViewCreated: _onQRViewCreated,
      overlay: QrScannerOverlayShape(
          borderColor: Colors.red,
          borderRadius: 10,
          borderLength: 30,
          borderWidth: 5,
          cutOutSize: MediaQuery.of(context).size.width - 120
          // cutOutSize: scanArea
      ),
      onPermissionSet: (ctrl, p) => _onPermissionSet(context, ctrl, p),
    );
  }

  void _onQRViewCreated(QRViewController controller) {
    setState(() {
      this.controller = controller;
    });
    controller.scannedDataStream.listen((scanData) {
      setState(() {
        result = scanData;
        content = ((result?.code == null) ? "" : result?.code!)!;
        // if(content.isEmpty){
        //   Fluttertoast.showToast(msg: "未识别到二维码");
        // } else {
          showResultPop();
        // }
      });
    });
  }

  late AnimationController animController;


  @override
  void initState() {
    super.initState();
    animController = AnimationController(vsync: this, duration: const Duration(milliseconds: 100));
    animController.addListener(() {
      if(animController.status == AnimationStatus.dismissed) {
        controller?.resumeCamera();
      } else if(animController.status == AnimationStatus.completed){
        controller?.pauseCamera();
      }
    });
  }

  Future showResultPop(){
    if(content.isEmpty){
      Fluttertoast.showToast(msg: "未识别出内容...");
      return Future(() => null);
    }

    return showModalBottomSheet(
      transitionAnimationController: animController,
        backgroundColor: Colors.transparent,
        context: context, builder: (context){
      return Container(
        height: 300,
        decoration: BoxDecoration(
            color: Colors.grey.withAlpha(200),
            borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(10),
                topRight: Radius.circular(10))),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
                top: 20,
                left: 20,
                child: GestureDetector(
                  child: const Icon(
                    Icons.arrow_back_ios,
                    color: Colors.white,
                  ),
                  onTap: () {
                    Navigator.pop(context);
                    // setState(() {
                    content = "";
                    // });
                  },
                )),
            SelectableText(
              content,
              style: const TextStyle(color: Colors.white),
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Padding(padding: const EdgeInsets.only(bottom: 20), child: ElevatedButton(
                  onPressed: () {
                    Fluttertoast.showToast(msg: "copy success...", textColor:Colors.black,backgroundColor: Colors.white);

                    // Clipboard.setData(ClipboardData(text: content));
                  },
                  child: const Text("复制内容")),),
            )
          ],
        ),
      );
    });
  }

  void _onPermissionSet(BuildContext context, QRViewController ctrl, bool p) {
    if (!p) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('no Permission')),
      );
    } else {
      if(content.isEmpty){//防止从识别图片返回导致的结果弹窗显示及仍在扫描问题
        controller?.resumeCamera();
      }
    }
  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }
}
